import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Typography,
  Badge,
  Tag,
  message,
  Breadcrumb,
} from 'antd';
import {
  MessageOutlined,
  EyeOutlined,
  PlusOutlined,
  TeamOutlined,
  HomeOutlined,
} from '@ant-design/icons';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { getSectionTopics, getForumSections } from '../../api/forum';
import { ForumTopic, ForumSection } from '../../types';
import { formatDateTime } from '../../utils/format';

const { Title, Text } = Typography;

const ForumTopics: React.FC = () => {
  const { sectionId } = useParams<{ sectionId: string }>();
  const [topics, setTopics] = useState<ForumTopic[]>([]);
  const [section, setSection] = useState<ForumSection | null>(null);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const navigate = useNavigate();

  useEffect(() => {
    if (sectionId) {
      fetchSection();
      fetchTopics();
    }
  }, [sectionId, pagination.current, pagination.pageSize]);

  const fetchSection = async () => {
    try {
      const response = await getForumSections();
      if (response.code === 200) {
        const currentSection = response.data.find(s => s.id === Number(sectionId));
        setSection(currentSection || null);
      }
    } catch (error) {
      console.error('获取板块信息失败:', error);
    }
  };

  const fetchTopics = async () => {
    try {
      setLoading(true);
      const response = await getSectionTopics(Number(sectionId), {
        page: pagination.current,
        size: pagination.pageSize,
      });

      if (response.code === 200) {
        setTopics(response.data.records);
        setPagination(prev => ({
          ...prev,
          total: response.data.total,
        }));
      }
    } catch (error) {
      console.error('获取主题列表失败:', error);
      message.error('获取主题列表失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '帖子',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: ForumTopic) => (
        <Space direction="vertical" size="small">
          <Space>
            {record.isTop && <Tag color="red">置顶</Tag>}
            {record.isEssence && <Tag color="gold">精华</Tag>}
            {record.isLocked && <Tag color="default">锁定</Tag>}
            <Link to={`/forum/topics/${record.id}`}>
              <Text strong>{title}</Text>
            </Link>
          </Space>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            by <Link to={`/user/${record.authorId}`}>{record.username}</Link> • {formatDateTime(record.createdAt)}
          </Text>
        </Space>
      ),
    },
    {
      title: '回复',
      dataIndex: 'replyCount',
      key: 'replyCount',
      width: 80,
      align: 'center' as const,
      render: (count: number) => (
        <Badge count={count} overflowCount={999} />
      ),
    },
    {
      title: '查看',
      dataIndex: 'viewCount',
      key: 'viewCount',
      width: 80,
      align: 'center' as const,
    },
  ];

  return (
    <div>
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">
            <HomeOutlined />
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/forum">
            <TeamOutlined /> 论坛
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          {section?.name}
        </Breadcrumb.Item>
      </Breadcrumb>

      <Card
        title={
          <Space>
            <MessageOutlined />
            <Title level={3} style={{ margin: 0 }}>
              {section?.name}
            </Title>
            {section?.description && (
              <Text type="secondary">- {section.description}</Text>
            )}
          </Space>
        }
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate(`/forum/new-topic?section=${sectionId}`)}
            >
              发表帖子
            </Button>
            <Link to="/forum">
              <Button>返回论坛</Button>
            </Link>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={topics}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || 20,
              }));
            },
          }}
        />
      </Card>
    </div>
  );
};

export default ForumTopics; 